package com.wwlwxg.spring_security.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@Slf4j
@RestController
public class FileController {

  /**
   * 文件上传
   * @param email
   * @param headerImg
   * @param photos
   * @return
   * @throws IOException
   */
  @PostMapping("/upload")
  public String upload(@RequestParam("email") String email,
                       @RequestPart("headerImg") MultipartFile headerImg,
                       @RequestPart("photos") MultipartFile[] photos) throws IOException {
    log.info("上传的信息： email = {}, headerImg = {}, photos = {}", email, headerImg.getSize(), photos.length);

    if(!headerImg.isEmpty()) {
      // 保存到文件服务器， OSS 服务器
      String originalFilename = headerImg.getOriginalFilename();
      File file = new File("logs\\" + originalFilename);
      headerImg.transferTo(file);
    }

    if(photos.length > 0) {
      for(MultipartFile photo : photos) {
        if(!photo.isEmpty()) {
          String originalFilename = photo.getOriginalFilename();
          photo.transferTo(new File("photo\\" + originalFilename));
        }
      }
    }

    return "main";
  }
}
